<template>
  <el-row :gutter="20" class="chart-section">
    <el-col :span="12">
      <el-card class="chart-card">
        <div class="chart-header">
          <span>用户增长趋势</span>
          <span class="total-count">总用户数: {{ userGrowthData.total || 0 }}人</span>
        </div>
        <div ref="userChart" class="chart"></div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="chart-card">
        <div class="chart-header">
          <span>商品分类分布</span>
          <span class="total-count">总分类数: {{ Object.keys(statData.categories).length }}个</span>
        </div>
        <div ref="salesChart" class="chart"></div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getItemStats, getUserGrowthStats } from '@/api/stat'


const userChart = ref<HTMLElement>()
const salesChart = ref<HTMLElement>()
let userChartInstance: echarts.ECharts | null = null
let salesChartInstance: echarts.ECharts | null = null

// 添加响应式数据存储统计结果
const statData = ref<{ total: number; categories: Record<string, number> }>({
  total: 0,
  categories: {}
})

const userGrowthData = ref<{ total: number; dates: string[]; counts: number[] }>({
  total: 0,
  dates: [],
  counts: []
})

// 获取统计数据
const getStatData = async () => {
  try {
    const [itemResponse, userResponse] = await Promise.all([
      getItemStats(),
      getUserGrowthStats()
    ])
    
    // 商品统计数据
    const itemData = itemResponse.data
    statData.value = {
      total: parseInt(itemData.total),
      categories: itemData.detail.reduce((acc: Record<string, number>, item: { category: string; count: string }) => {
        acc[item.category] = parseInt(item.count)
        return acc
      }, {})
    }

    // 用户增长数据
    const userData = userResponse.data
    userGrowthData.value = {
      total: parseInt(userData.total),
      dates: userData.detail.dates.map((date: string) => {
        // 将日期字符串转换为 MM-DD 格式
        const [year, month, day] = date.split('-')
        return `${month}-${day}`
      }),
      counts: userData.detail.counts.map((count: string) => parseInt(count))
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    statData.value = {
      total: 0,
      categories: {}
    }
    userGrowthData.value = {
      total: 0,
      dates: [],
      counts: []
    }
  }
}

// 初始化用户图表
const initUserChart = () => {
  if (!userChart.value) return
  
  userChartInstance = echarts.init(userChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />新增用户数：{c}'
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: userGrowthData.value.dates.length ? userGrowthData.value.dates : ['暂无数据'],
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      }
    },
    yAxis: {
      type: 'value',
      name: '新增用户数',
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      },
      splitLine: {
        show: true
      }
    },
    series: [{
      data: userGrowthData.value.counts.length ? userGrowthData.value.counts : [0],
      type: 'line',
      smooth: true,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(255, 105, 180, 0.3)' },
          { offset: 1, color: 'rgba(255, 209, 255, 0.1)' }
        ])
      },
      itemStyle: {
        color: '#ff69b4'
      },
      lineStyle: {
        width: 2,
        color: '#ff69b4'
      }
    }]
  }
  userChartInstance.setOption(option)
}

const initSalesChart = async () => {
  if (!salesChart.value) return

  await getStatData()
  salesChartInstance = echarts.init(salesChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}件'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center',
      type: 'scroll'
    },
    series: [{
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['60%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: Object.entries(statData.value.categories)
        .sort(([, a], [, b]) => b - a)
        .map(([name, value]) => ({
          name,
          value
        }))
    }]
  }
  salesChartInstance.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  userChartInstance?.resize()
  salesChartInstance?.resize()
}

onMounted(async () => {
  // 先获取数据
  await getStatData()

  // 使用 setTimeout 确保 DOM 已完全渲染
  setTimeout(() => {
    initUserChart()
    initSalesChart()
    window.addEventListener('resize', handleResize)
  }, 100)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  userChartInstance?.dispose()
  salesChartInstance?.dispose()
})
</script>

<style scoped>
.chart-section {
  margin-bottom: 20px;
  height: 400px; /* 添加固定高度 */
}

.chart-card {
  padding: 20px;
  height: 100%; /* 使用父容器高度 */
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
}

.total-count {
  font-size: 14px;
  color: #606266;
  font-weight: normal;
}

.chart {
  height: calc(100% - 56px);
  width: 100%;
  min-height: 300px; /* 添加最小高度 */
}

.el-col {
  padding: 10px;
  height: 100%; /* 确保列也有高度 */
}
</style>
